#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2020-05-28

@author: zhuyu
"""
import os
import time

GOLF_APP_LIST = [
        'com.alipay.iot.master',
        'com.alipay.iot.ic',
        'com.alipay.iot.service',
        'com.alipay.iot.osupdate',
        'com.alipay.iot.systemcommand',
        'com.alipay.iot.osupdate',
        'com.alipay.iot.master:monitor',
        'com.alipay.iot.master:worker',
        'com.alipay.mapp.content.service',
        'com.alipay.iot.settings',
        # 'zoloz.phone.android.alipay.com.dragonfly',
        'com.alipay.zoloz.smile',
        'com.alipay.iot.connect',
        'com.alipay.iot.xpaas'
]


def gettime():
    time.localtime(time.time())
    timestamp = time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime(time.time()))
    return timestamp


def get_app_version():
    appinfo = {}
    lines = os.popen("adb shell pm list packages |grep alipay ").readlines()
    for line in lines:
        version_value = ''
        packagename = line.replace('package:', '').strip(' ').strip('\n')
        versioninfos = os.popen("adb shell dumpsys package {}|grep versionName".format(packagename)).readlines()
        for version in versioninfos:
            if 'versionName' in version:
                version_value = version_value + version.replace('versionName=', '').strip('\n').strip(' ')
        appinfo[packagename] = version_value
    for package in appinfo:
        print package, ':', appinfo[package]


def get_app_pid(appname):
    lines = os.popen("adb shell ps |grep {} ".format(appname)).readlines()
    if len(lines) == 0:
        print 'get app pid fail {}'.format(appname)
        return
    for line in lines:
        pro_info = line.split(' ')
        while '' in pro_info:
            pro_info.remove('')
        app_pid = pro_info[1]
        appname_temp = pro_info[-1].strip('\n')
        if appname == appname_temp:
            return app_pid


def kill_app(appName):
    os.popen("adb shell am force-stop {}".format(appName))
    if appName == 'com.alipay.iot.ic':
        time.sleep(30)
    else:
        time.sleep(6)


def kill_antapp_test():
    for appname in GOLF_APP_LIST:
        pid1 = get_app_pid(appname)
        if pid1 is not None:
            kill_app(appname)
        else:
            continue
        pid2 = get_app_pid(appname)
        if pid2 is not None and pid1 != pid2:
            print 'test app success {} pid is {}->{}'.format(appname, pid1, pid2)


if __name__ == '__main__':
    for i in range(10):
        kill_antapp_test()
